﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace DeviceController.Wpf.ViewModels.UserManageViewModels
{
    public class UserViewModel
    {
        public bool IsChecked { get; set; }

        public string Number { get; set; } = string.Empty;

        public UserPermessions Permession { get; set; }
    }

    public class UserListViewModel : ObservableObject
    {
        private readonly UserManager _userManager;

        public UserListViewModel(UserManager userManager)
        {
            _userManager = userManager;
            UpdateCommand = new RelayCommand(OnUpdate);
            RemoveCommand = new RelayCommand(OnRemove);
            Users = new ObservableCollection<UserViewModel>(GetAll());
        }

        private List<UserViewModel> GetAll()
        {
            return _userManager.GetAll().Select(user => new UserViewModel()
            {
                Number = user.Number,
                Permession = user.Permession
            }).ToList();
        }

        private ObservableCollection<UserViewModel> _users;

        public ObservableCollection<UserViewModel> Users
        {
            get => _users;
            set => SetProperty(ref _users, value);
        }

        public ICommand UpdateCommand { get; set; }

        private void OnUpdate()
        {
            Users = new ObservableCollection<UserViewModel>(GetAll());
        }

        public ICommand RemoveCommand { get; set; }

        private void OnRemove()
        {
            var users = Users.Where(user => user.IsChecked);

            if (users.Any())
            {
                var result = MessageBox.Show("您确定要删除这些用户吗？", "删除提示", MessageBoxButton.YesNo);

                if (result == MessageBoxResult.Yes)
                {
                    _userManager.RemoveRange(users.Select(user => user.Number).ToList());

                    // 删除之后更新用户列表。
                    Users = new ObservableCollection<UserViewModel>(GetAll());
                }
            }
        }
    }
}
